import { escapeDeal } from '@/views/youshuda/utils/youshuda'
import request from '@/utils/request'
import { getYsdApiData } from '@/views/youshuda/api/BaseApi'
import store from '@/store'
import { EventBus } from '@/views/youshuda/utils/event-bus';
import { Toast, Dialog, Notify } from 'vant'

export const MobileEventMixins = {
  components: {},
  props: {},
  computed: {},
  data() {
    return {
      //表单设计字段配置信息
      pageBuildConfig: [],
      //页面表单数据
      pageFormData: {},
      //组件执行方法时的参数
      compFuncParams: null,
    }
  },
  created() {
  },
  methods: {
    /** 执行事件对应逻辑 **/
    evalEventCode(eventCode,params) {
      this.compFuncParams = params ? params : null
      if (eventCode) {
        /** 特殊字符处理 **/
        eventCode = escapeDeal(eventCode);
        // 创建函数对象
        const func = new Function(eventCode);
        return func.call(this);
      }
    },
    /** Get请求服务器数据 **/
    axiosGet(url) {
      if (!this.strIsNotEmpty(url)) {
        this.msgError("Get请求地址不能为空");
        return;
      }
      return request({url: url, method: 'get'})
    },
    /** Post请求服务器数据 **/
    axiosPost(url, data) {
      if (!this.strIsNotEmpty(url)) {
        this.msgError("Post请求地址不能为空");
        return;
      }
      return request({url: url, method: 'post', data: data})
    },
    /** 请求优树搭接口数据 **/
    getYsdApiData(procTarget,reqData){
      if (!this.strIsNotEmpty(procTarget)) {
        this.msgError("优树搭API编码不能为空");
        return;
      }
      return getYsdApiData(procTarget,reqData);
    },
    /** 获取当前登录用户 **/
    getUserName() {
      return store.getters.name;
    },
    /** 获取当前登录用户角色 **/
    getUserRoles() {
      return store.getters.roles;
    },
    /** 获取表单字段值 **/
    getFieldValue(fieldName,formName) {
      if(!formName){formName = 'mobileForm'}
      if (fieldName) {
        return this.pageFormData[formName][fieldName];
      }
      return '';
    },
    /** 获取表单数据 **/
    getFormValue(formName) {
      if(!formName){formName = 'mobileForm'}
      return this.pageFormData[formName]
    },
    /** 设置表单字段值 **/
    setFieldValue(fieldName, fieldValue,formName) {
      if(!formName){formName = 'mobileForm'}
      if (fieldName) {
        this.$set(this.pageFormData[formName] ,fieldName, fieldValue)
        this.changeFieldConfigValue(fieldName, 'fieldValue', fieldValue, true)
      }
    },
    /** 设置表单数据 **/
    setFormValue(data,formName) {
      if(!formName){formName = 'mobileForm'}
      for (const key in data) {
        this.setFieldValue(key, data[key],formName)
      }
    },
    /** 改变element对象值 **/
    changeFieldConfigValue(fieldName, key, val, isDealOnChangeEvent) {
      if(!Array.isArray(this.pageBuildConfig)){
        return;
      }
      let that = this
      if (this.strIsEmpty(fieldName)) {
        this.msgError("处理字段不能为空");
        return;
      }
      let isFind=false;
      function findColumn(formBuildConfig){
        for (let field of formBuildConfig) {
          if (field && (field['vModel'] == fieldName || field['formId'] == fieldName)) {
            that.$set(field, key, val)
            //如果是修改字段值，则需要同时修改defaultValue
            if(key == 'fieldValue'){
              that.$set(field, 'defaultValue', val)
              /** 当存在onChange事件处理时，则处理相关 **/
              if(isDealOnChangeEvent && field['onChange']){
                that.evalEventCode(field['onChange']);
              }
            }
            isFind=true;
            return;
          }
          if(field.children && Array.isArray(field.children) && field.children.length>0){
            findColumn(field.children)
            if(isFind){
              return;
            }
          }
        }
      }
      findColumn(this.pageBuildConfig);
    },
    /** 显示组件 **/
    showField(fieldName) {
      this.changeFieldConfigValue(fieldName, 'isShow',true)
    },
    /** 隐藏主键 **/
    hideField(fieldName) {
      this.changeFieldConfigValue(fieldName, 'isShow',false)
    },
    /** 设置禁用 **/
    setDisabled(fieldName) {
      this.changeFieldConfigValue(fieldName, 'disabled',true)
    },
    /** 取消禁用 **/
    cancelDisabled(fieldName) {
      this.changeFieldConfigValue(fieldName, 'disabled',false)
    },
    /** 提交表单 **/
    submitForm(formName) {
      let  refs = this.$refs['mobilePageRender'];
      refs.forEach(item=>{
        if(item.$refs[formName]){
          item.$refs[formName].submit()
          return;
        }
      })
    },
    /** 消息提示 **/
    showToast(msgObj){
      //msgObj = {type:}
      // this.uni.postMessage({
      //   data: {
      //     type: 'showMsg',
      //     data: msgObj
      //   }
      // })
      Toast(msgObj)
    },
    /** 隐藏提示 **/
    hideToast(){
      Toast.clear()
      // this.uni.postMessage({
      //   data: {
      //     type: 'hideMsg'
      //   }
      // })
    },
    /** 设置剪切板 **/
    setClipboardData(data){
      let busName = this.generateUuid();
      return (
        new Promise((resolve, reject) => {
          data['busName'] = busName;
          //调用uni-app 插件
          this.uni.postMessage({
            data: {
              type: 'setClipboard',
              data: data
            }
          })
          //创建监听
          EventBus.$on(busName, (e) => {
            if (e.state == 'success') {
              resolve(e)
            } else {
              reject(e)
            }
          })
        }).finally(()=>{
          //关闭监听
          EventBus.$off(busName);
        })
      )
    },
    /** 获取剪切板 **/
    getClipboardData(){
      let busName = this.generateUuid();
      let data = {};
      return (
        new Promise((resolve, reject) => {
          data['busName'] = busName;
          //调用uni-app 插件
          this.uni.postMessage({
            data: {
              type: 'getClipboard',
              data: data
            }
          })
          //创建监听
          EventBus.$on(busName, (e) => {
            if (e.state == 'success') {
              resolve(e.res)
            } else {
              reject(e)
            }
          })
        }).finally(()=>{
          //关闭监听
          EventBus.$off(busName);
        })
      )
    },
    /** 扫码 **/
    scanCode(){
      let busName = this.generateUuid();
      let data = {};
      return (
        new Promise((resolve, reject) => {
          data['busName'] = busName;
          //调用uni-app 插件
          this.uni.postMessage({
            data: {
              type: 'scanCode',
              data: data
            }
          })
          //创建监听
          EventBus.$on(busName, (e) => {
            if (e.state == 'success') {
              resolve(e.res)
            } else {
              reject(e)
            }
          })
        }).finally(()=>{
          //关闭监听
          EventBus.$off(busName);
        })
      )
    },
    /** 隐藏软件键盘 **/
    hideKeyboard(){
      this.uni.postMessage({
        data: {
          type: 'hideKeyboard'
        }
      })
    },
    /** 跳转页面 */
    navigateTo(pageKey,params) {
      // this.$router.push("/ysdAppRender/mobilePageRender/"+pageKey)
      this.$router.push({ path: "/ysdAppRender/mobilePageRender/"+pageKey, query: params})
    },
    /** 返回页面 */
    navigateBack(n) {
      n = -(n || 1);
      this.$router.go(n)
    },
    /** 设置底部导航栏徽标信息 */
    setTabBarBadge(pageKey,index,data) {
      if(!Array.isArray(this.pageBuildConfig)){
        return;
      }
      let that = this;
      let carrPageKey =  this.$route.params.pageKey;
      let isFind=false;
      function findColumn(formBuildConfig){
        for (let field of formBuildConfig) {
          if (carrPageKey == pageKey) {
            let bottomTabBar = field['bottomTabBar']
            let item = bottomTabBar[index-1];
            item.badge = data.badge;
            item.dot = data.dot;
            bottomTabBar[index-1] = item;
            that.$set(field, 'bottomTabBar', bottomTabBar);
            isFind=true;
            return;
          }
          if(field.children && Array.isArray(field.children) && field.children.length>0){
            findColumn(field.children)
            if(isFind){
              return;
            }
          }
        }
      }
      findColumn(this.pageBuildConfig);
    },
    /** 关闭下拉刷新 */
    closePullDownRefresh() {
      if(!Array.isArray(this.pageBuildConfig)){
        return;
      }
      let that = this;
      let isFind=false;
      function findColumn(formBuildConfig){
        for (let field of formBuildConfig) {
          if (field && field['moduleType'] == 'van-pull-refresh' && !field['disabled'] && field['fieldValue']) {
            that.$set(field, 'fieldValue', false);
            isFind=true;
            return;
          }
          if(field.children && Array.isArray(field.children) && field.children.length>0){
            findColumn(field.children)
            if(isFind){
              return;
            }
          }
        }
      }
      findColumn(this.pageBuildConfig);
    },
    /** 重新加载当前页面 */
    reloadPage() {
      this.initPage();
      setTimeout(()=>{
        this.closePullDownRefresh();
      },500)
    },
    /** 设置组件值 **/
    setModuleValue(moduleName, data) {
      this.$set(this.pageFormData ,moduleName, data)
      this.changeFieldConfigValue(moduleName, 'fieldValue', data, true)
    },
    /** 获取组件值 **/
    getModuleValue(moduleName) {
      let _data = this.pageFormData[moduleName];
      if(_data){
        return _data;
      }
      _data = null;
      if(!Array.isArray(this.pageBuildConfig)){
        return null;
      }
      let isFind=false;
      function findColumn(formBuildConfig){
        for (let field of formBuildConfig) {
          if (field && (field['vModel'] == moduleName || field['formId'] == moduleName)) {
            isFind=true;
            _data = field['fieldValue'];
            return;
          }
          if(field.children && Array.isArray(field.children) && field.children.length>0){
            findColumn(field.children)
            if(isFind){
              return;
            }
          }
        }
      }
      findColumn(this.pageBuildConfig);
      return _data;
    },
    /** 无限滚动加载完成 **/
    infiniteScrollComplete() {
      if(!Array.isArray(this.pageBuildConfig)){
        return;
      }
      let that = this;
      let isFind=false;
      function findColumn(formBuildConfig){
        for (let field of formBuildConfig) {
          if (field && field['moduleType'] == 'van-list' && !field['finished'] && field['fieldValue']) {
            that.$set(field, 'finished', true);
            isFind=true;
            return;
          }
          if(field.children && Array.isArray(field.children) && field.children.length>0){
            findColumn(field.children)
            if(isFind){
              return;
            }
          }
        }
      }
      findColumn(this.pageBuildConfig);
    },
    /** 无限滚动加载失败 **/
    infiniteScrollError(msg) {
      if(!Array.isArray(this.pageBuildConfig)){
        return;
      }
      let that = this;
      let isFind=false;
      function findColumn(formBuildConfig){
        for (let field of formBuildConfig) {
          if (field && field['moduleType'] == 'van-list' && !field['finished'] && field['fieldValue']) {
            that.$set(field, 'error', true);
            that.$set(field, 'errorText', msg);
            isFind=true;
            return;
          }
          if(field.children && Array.isArray(field.children) && field.children.length>0){
            findColumn(field.children)
            if(isFind){
              return;
            }
          }
        }
      }
      findColumn(this.pageBuildConfig);
    },
    /** 获取组件refs **/
    getRefs(fieldName){
      return this.$refs[fieldName];
    },
    /** 设置级联组件选项 **/
    setCascadeOptions(fieldName, options){
      this.changeFieldConfigValue(fieldName, 'options', options, false)
    },
    /** 设置页面数据 **/
    setPageData(data){
      if(data){
        for (const key in data) {
          this.changeFieldConfigValue(key, 'fieldValue', data[key], false)
        }
      }
    },
    /** 设置组件渲染数据 **/
    setFieldRendData(fieldName,data){
      if(data){
        this.changeFieldConfigValue(fieldName, 'defaultData', data, false)
      }
    },
    /** 打开弹出窗 **/
    openDialog(data) {
      if(data.type=='alert'){//消息弹框
        return Dialog.alert({...data});
      }else if(data.type=='confirm'){//确认弹框
        return Dialog.confirm({...data});
      }else{//自定义弹框
        return Dialog({...data});
      }
    },
    /** 关闭弹出窗 **/
    closeDialog() {
      Dialog.close();
    },
    /** 发送通知 **/
    openNotify(data) {
      Notify(data)
    },
    /** 关闭通知 **/
    closeNotify() {
      Notify.clear()
    }
  }
}
